package org.richin.servlet.Filter.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * 写个filter,让你在哪怕是javabean中都可以随便读取http请求信息
 * @author Administrator
 *
 */
public class CommonFilter implements Filter {
	private FilterConfig config = null;
	private String defaultEncode = "UTF-8";
	private static final String CHARSET_ENCODE_PARAM_NAME = "Charset";

	private static ThreadLocal<HttpServletRequest> requests = new ThreadLocal<HttpServletRequest>();
	private static ThreadLocal<HttpServletResponse> responses = new ThreadLocal<HttpServletResponse>();

	public void destroy() {
		this.config = null;

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		ServletRequest srequest = request;
		srequest.setCharacterEncoding(defaultEncode);
		requests.set((HttpServletRequest) request);
		responses.set((HttpServletResponse) response);
		chain.doFilter(srequest, response);

	}

	public void init(FilterConfig config) throws ServletException {
		this.config = config;
		if (this.config.getInitParameter(CHARSET_ENCODE_PARAM_NAME) != null) {
			defaultEncode = config.getInitParameter(CHARSET_ENCODE_PARAM_NAME);
		}
	}

	public static HttpServletRequest getRequest() {
		return requests.get();
	}

	public static HttpServletResponse getResponse() {
		return responses.get();
	}

	public static HttpSession getSession() {
		return getRequest().getSession();
	}

	public static HttpSession getSession(boolean create) {
		return getRequest().getSession(create);
	}

}
